package cn.iocoder.yudao.module.picturebook.controller.admin.wechat;


import cn.iocoder.yudao.module.picturebook.config.WechatConfig;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.wechat.WechatToken;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.wechat.WechatUserInfo;
import cn.iocoder.yudao.module.picturebook.service.wechat.WechatService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Tag(name = "微信接口", description = "微信相关操作")
@RestController
@RequestMapping("/wechat")
public class WechatController {

    private final WechatConfig wechatConfig;
    private final WechatService wechatService;

    public WechatController(WechatConfig wechatConfig, WechatService wechatService) {
        this.wechatConfig = wechatConfig;
        this.wechatService = wechatService;
    }

    /**
     * 生成微信登录URL，前端重定向到该URL
     */
    @Operation(summary = "生成微信登录URL")
    @GetMapping("/login")
    public String generateWechatLoginUrl() {
        // 构建微信登录URL，包含appid、redirect_uri等参数
        String redirectUri = "http://192.0.0.1:48080/admin_api/wechat/callback";
        String state = "STATE"; // 自定义状态参数，防止CSRF攻击

        return wechatConfig.getAuthUrl() +
                "?appid=" + wechatConfig.getAppId() +
                "&redirect_uri=" + redirectUri +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=" + state +
                "#wechat_redirect";
    }

    /**
     * 微信登录回调接口，接收code参数
     */
    @Operation(summary = "微信登录回调接口")
    @GetMapping("/callback")
    public void handleWechatCallback(@RequestParam("code") String code,
                                     @RequestParam("state") String state,
                                     HttpServletResponse response) throws IOException {
        // 使用code换取access_token和openid
        WechatToken token = wechatService.getAccessToken(code);

        // 使用access_token和openid获取用户信息
        WechatUserInfo userInfo = wechatService.getUserInfo(token.getAccessToken(), token.getOpenId());

        // 这里可以根据业务需求处理用户信息，如注册或登录用户
        // ...

        // 登录成功后，重定向到前端页面或返回token
        response.sendRedirect("http://your-frontend.com/login-success?token=" + "your_generated_token");
    }
}